package zx.x.modules.yshapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import zx.x.common.utils.PageUtils;
import zx.x.common.utils.Query;
import zx.x.modules.app.dao.UserDao;
import zx.x.modules.app.entity.UserEntity;
import zx.x.modules.yshapp.dao.PointAppDao;
import zx.x.modules.yshapp.entity.GoodsEntity;
import zx.x.modules.yshapp.entity.PointEntity;
import zx.x.modules.yshapp.service.PointService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service("pointAppService")
public class PointAppServiceImpl extends ServiceImpl<PointAppDao, PointEntity> implements PointService {

    @Autowired
    PointAppDao pointAppDao;
    @Autowired
    private UserDao userDao;
    @Override
    public List<PointEntity> getMonthlyPoint(Map<String, Object> params) {
        Integer userId = Integer.parseInt(params.get("userId").toString());
        String date = (String) params.get("yearMonth");//某年某月
        String yearMonth = date;
        date = date+"-01";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<PointEntity> pointList = new ArrayList<>();
        List<PointEntity> points = new ArrayList<>();
        try {
            Date firstDate = sdf.parse(date);
            Calendar cld = Calendar.getInstance();
            cld.setTime(firstDate);
            cld.add(Calendar.MONTH, 1);
            cld.set(Calendar.DAY_OF_MONTH, 1);
            Date lastDay = cld.getTime();
            pointList = pointAppDao.getMonthlyPoint(userId,firstDate,lastDay);
            if( pointList !=null && pointList.size()>0 ){
                String[] time = date.split("-");
                int dateNum = getMonthDayNum(time[0],time[1]);

                SimpleDateFormat dd = new SimpleDateFormat("dd");

                for (int i = 1; i <=dateNum; i++) {
                    PointEntity pointEntity = new PointEntity();
                    String d1;
                    if(i < 10){
                        d1= "0"+i;
                    }else{
                        d1= i+"";
                    }
                    int flag = 0;
                    for (int j = 0; j < pointList.size(); j++) {
                        Date d = pointList.get(j).getCjTime();
                        String d2 = dd.format(d);
                        if(d1.equals(d2)){
                            flag = 1;
                            pointEntity = pointList.get(j);
                            break;
                        }
                    }
                    if(flag == 0){
                        String timeStr =yearMonth + "-" +d1;
                        pointEntity.setCjTime(sdf.parse(timeStr));
                        pointEntity.setPoint(0);
                        points.add(pointEntity);
                    }else{
                        points.add(pointEntity);
                    }
                }

            }

        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        return points;
    }

    @Override
    @Transactional
    public int signIn(Integer userId) {

        int point = 0;
        int[] signInfo = getSignInInfo(userId);
        if(signInfo[1] == 1){//今天已签到
            return point;
        }
        int userType =signInfo[2];
        int signIndays = signInfo[0];
        if(userType == 1|| userType == 2){//vip和svip
            point = 1<< (signIndays+1);
        }else{
            point = 1<< signIndays;
        }

        PointEntity pointEntity = new PointEntity();
        pointEntity.setState(0);
        pointEntity.setUserId(userId);
        pointEntity.setSource(1);
        Date currentDate = new Date();
        pointEntity.setCjTime(currentDate);
        pointEntity.setPoint(point);
        pointAppDao.insert(pointEntity);

        UserEntity user = userDao.selectById(userId);
        Calendar cld = Calendar.getInstance();
        cld.add(Calendar.DATE, -1);


        if(user.getLastSignInTime() != null
                && user.getLastSignInTime().getYear() == cld.getTime().getYear()
                && user.getLastSignInTime().getMonth() == cld.getTime().getMonth()
                && user.getLastSignInTime().getDate() == cld.getTime().getDate()){//昨天签到了
            user.setSignInDays(user.getSignInDays()+1);
        }else{//昨天没签到
            user.setSignInDays(1);
        }

        if(user.getPoint() == null){
            user.setPoint(point);
        }else{
            user.setPoint(user.getPoint()+point);
        }
        user.setLastSignInTime(currentDate);
        userDao.updateById(user);


        return point;
    }


    @Override
    public int signIndays(Integer userId) {
        return getSignInInfo(userId)[0];
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<PointEntity> pointEntityQueryWrapper = new QueryWrapper<>();
        pointEntityQueryWrapper.eq("source",1)
                .eq("user_id",Integer.parseInt(params.get("userId").toString()))
                .orderBy(true,false,"cj_time");
        IPage<PointEntity> page = this.page(
                new Query<PointEntity>().getPage(params),
                pointEntityQueryWrapper
        );
        return new PageUtils(page);
    }

    public int[] getSignInInfo(Integer userId){
        int isToday = 0;//今天签到1，没签到0
        int signIndays = 0;//连续签到天数
        UserEntity user = userDao.selectById(userId);


        if(user.getLastSignInTime() != null){
            Calendar cld = Calendar.getInstance();
            for(int i = 0;i<2;i++){

                if( i == 0){
                    if(user.getLastSignInTime().getYear() == cld.getTime().getYear()
                            && user.getLastSignInTime().getMonth() == cld.getTime().getMonth()
                            && user.getLastSignInTime().getDate() == cld.getTime().getDate()){
                        isToday = 1;
                        signIndays = user.getSignInDays()%7;
                        if(signIndays == 0){
                            signIndays = 7;
                        }
                        break;
                    }else {
                        cld.add(Calendar.DATE, -1);
                    }
                }

                if(i == 1){
                    if(user.getLastSignInTime().getYear() == cld.getTime().getYear()
                            && user.getLastSignInTime().getMonth() == cld.getTime().getMonth()
                            && user.getLastSignInTime().getDate() == cld.getTime().getDate()){//昨天签到
                        signIndays = user.getSignInDays()%7;
                        break;
                    }
                }
            }
        }

        return new int[]{signIndays,isToday,user.getType()} ;
    }


    public int getMonthDayNum(String year ,String month){
        int dayNum = 0;
        switch (month){
            case "01":
            case "03":
            case "05":
            case "07":
            case "08":
            case "10":
            case "12":
                dayNum = 31;
                break;
            case "04":
            case "06":
            case "09":
            case "11":
                dayNum = 30;
                break;
            case "02":
                Integer y=Integer.valueOf(year);
                if(y % 4 == 0 && y % 100 != 0 || y % 400 ==0){
                    dayNum = 29;
                }else{
                    dayNum = 28;
                }
                break;
            default:
                break;
        }
        return dayNum;
    }





}